﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Threading;

namespace System.Web
{
    /// <summary>
    /// Provides a set of extension methods for the <see cref="System.Web.UI.Page"/> class to help
    /// manage routed requests.
    /// </summary>
    public static class HttpHandlerExtensions
    {
        [ThreadStatic] // On instance per thread.
        private static RequestContext requestContext;

        /// <summary>
        /// Assigns the request context.
        /// </summary>
        /// <param name="httpHandler">The HTTP handler.</param>
        /// <param name="requestContext">The request context.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes", Justification = "Prevents null reference invocations.")]
        internal static void AssignRequestContext(this IHttpHandler httpHandler, RequestContext requestContext)
        {
            if (httpHandler == null)
                throw new NullReferenceException();

            if (requestContext == null)
                throw new ArgumentNullException("requestContext");

            HttpHandlerExtensions.requestContext = requestContext;
        }

        /// <summary>
        /// Determines whether the specified page is routed.
        /// </summary>
        /// <param name="httpHandler">The HTTP handler.</param>
        /// <returns>
        /// 	<c>true</c> if the specified page is routed; otherwise, <c>false</c>.
        /// </returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
        public static bool IsRouted(this IHttpHandler httpHandler)
        {
            if (httpHandler == null)
                throw new NullReferenceException();

            return requestContext != null;
        }

        /// <summary>
        /// Gets the request context.
        /// </summary>
        /// <param name="httpHandler">The HTTP handler.</param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
        public static RequestContext GetRequestContext(this IHttpHandler httpHandler)
        {
            if (httpHandler == null)
                throw new NullReferenceException();

            if (requestContext == null)
                throw new InvalidOperationException(MyClub.Web.Properties.Resources.PageExtensions_MissingRequestContext);

            return requestContext;
        }
    }
}
